package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.MonitorInputAdapter;
import com.hxkcloud.patient.beans.MonitorInputValueBean;
import com.hxkcloud.patient.beans.MonitorKindBean;
import com.hxkcloud.patient.dborm.MonitorKindDao;
import com.hxkcloud.patient.popup.DateTimeSelectPopWindow;
import com.hxkcloud.patient.popup.MonitorInputPopWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.Utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by william_sun on 2016-08-04.
 * Description:患者监测项录入
 */
public class MonitorInputActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;

    private TextView tv_time;
    private LinearLayout ll_kind;
    private TextView tv_test;
    private RecyclerView rv;
    private Button bt_save;

    private DateTimeSelectPopWindow datetimeSelect;
    private MonitorInputPopWindow monitorInputPopWindow;

    private String monitorId;
    private MonitorKindBean kind;
    private MonitorInputAdapter adapter;

    private String testId;//选择的餐前或餐后

    //两个按钮
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;

    private boolean isTimeInput = false;
    private boolean isValueInput = false;

    private String currentDate;

    private boolean isTestIdInput = false;
    private String orderId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitorinput);
        if (getIntent().hasExtra("orderId")) {
            orderId = getIntent().getStringExtra("orderId");
        }
        monitorId = this.getIntent().getStringExtra("monitorId");
        MonitorKindDao monitorKindDao = new MonitorKindDao(mContext);
        kind = monitorKindDao.getKind(monitorId);
        if (kind == null) {
            toastMsg(R.string.cantfindmonitordata);
            finish();
            return;
        }
        initView();
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_PATIENTMONITORADD_SUCCESS:
                YiJiaHuNetWorkUtils.execOrder(orderId);
                if (msg.obj != null) {
                    Intent iBack = new Intent();
                    setResult(RESULT_OK, iBack);
                    finish();
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.datainputsuccess));
                }

                break;
            case MessageCode.NETWORKCODE_PATIENTMONITORADD_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.datainputfail));
                }
                break;
        }
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        if (kind != null) {
            tv_title.setText(kind.getName() + "录入");
        }

        iv_back.setOnClickListener(this);

        tv_time = (TextView) findViewById(R.id.tv_monitorinput_time);
        ll_kind = (LinearLayout) findViewById(R.id.ll_monitorinput_kind);
        tv_test = (TextView) findViewById(R.id.tv_monitorinput_kind);
        rv = (RecyclerView) findViewById(R.id.rv_monitorinput);
        bt_save = (Button) findViewById(R.id.bt_monitorinput_save);

        tv_time.setOnClickListener(this);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        currentDate = df.format(new Date());
        tv_time.setText(currentDate);
        isTimeInput = true;

        if (kind != null) {
            if (kind.getTestList() != null && kind.getTestList().size() > 0) {
                ll_kind.setVisibility(View.VISIBLE);
//                tv_test.setText(kind.getTestList().get(0).getName());
//                testId = kind.getTestList().get(0).getTestId();
                tv_test.setText(mContext.getResources().getString(R.string.input_leixing));
                isTestIdInput = false;
                tv_test.setOnClickListener(this);
            } else {
                isTestIdInput = true;
                ll_kind.setVisibility(View.GONE);
            }
        }


        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(mLayoutManager);
        adapter = new MonitorInputAdapter(mContext, kind);
        adapter.setListener(new MonitorInputAdapter.onWordsChangeListener() {
            @Override
            public void showGreen() {
                isValueInput = true;
                if (isTimeInput && isTestIdInput) {
                    bt_save.setBackgroundResource(R.drawable.bt_green);
                    bt_save.setEnabled(true);
                } else {
                    bt_save.setBackgroundResource(R.drawable.bt_grey);
                    bt_save.setEnabled(false);
                }
            }

            @Override
            public void showGrey() {
                isValueInput = false;
                bt_save.setBackgroundResource(R.drawable.bt_grey);
                bt_save.setEnabled(false);
            }
        });
        rv.setAdapter(adapter);

        bt_save.setOnClickListener(this);

        datetimeSelect = new DateTimeSelectPopWindow(this);
        datetimeSelect.setTimeListener(new DateTimeSelectPopWindow.TimeListener() {
            @Override
            public void setTime(String time) {
                String timeStr = "";
                if (time.contains(".")) {
                    timeStr = time.replace(".", "-");
                }

//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//                String currentDate = df.format(new Date());
                int i = compareDate(currentDate, timeStr, "yyyy-MM-dd HH:mm");
                if (i == 0 || i == 1) {
                    tv_time.setText(timeStr);
                    isTimeInput = true;
                } else {
                    toastMsg(R.string.input_right_date);
                }

                if (isValueInput) {
                    bt_save.setBackgroundResource(R.drawable.bt_green);
                    bt_save.setEnabled(true);
                } else {
                    bt_save.setBackgroundResource(R.drawable.bt_grey);
                    bt_save.setEnabled(false);
                }
            }
        });
        if (kind != null) {

            monitorInputPopWindow = new MonitorInputPopWindow(this, kind.getTestList());
            monitorInputPopWindow.setListener(new MonitorInputPopWindow.onTestSelectListener() {
                @Override
                public void select(int position) {
                    tv_test.setText(kind.getTestList().get(position).getName());
                    testId = kind.getTestList().get(position).getTestId();
                    isTestIdInput = true;
                    if (isValueInput && isTestIdInput) {
                        bt_save.setBackgroundResource(R.drawable.bt_green);
                        bt_save.setEnabled(true);
                    } else {
                        bt_save.setBackgroundResource(R.drawable.bt_grey);
                        bt_save.setEnabled(false);
                    }
                }
            });

        }


        //easynotice
        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(MonitorInputActivity.this);
            }
        });

    }

    public int compareDate(String DATE1, String DATE2, String format) {

        DateFormat df = new SimpleDateFormat(format);
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                String[] vss = adapter.getValues();
                boolean isSet = false;//是否有输入内容
                for (int i = 0; i < vss.length; i++) {
                    if (!TextUtils.isEmpty(vss[i])) {
                        isSet = true;
                        break;
                    }
                }
                if (!tv_time.getText().toString().trim().equals(currentDate)) {
                    isSet = true;
                }
                if (isSet) {
                    tv_easynotice_title.setText(getResources().getString(R.string.data_exit));
                    tv_easynotice_cancel.setText(getResources().getString(R.string.cancel));
                    tv_easynotice_func.setText(getResources().getString(R.string.data_sure));
                    popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                    BrightnessUtils.lightOff(this);
                } else {
                    finish();
                }

                break;
            case R.id.tv_monitorinput_time:
                Utils.hideSoftInputFromWindow(this);
                datetimeSelect.show(ll_title);
                break;
            case R.id.tv_monitorinput_kind:
                Utils.hideSoftInputFromWindow(this);
                monitorInputPopWindow.show(ll_title);
                break;
            case R.id.bt_monitorinput_save:
                String time = tv_time.getText().toString().trim();
                if (TextUtils.isEmpty(time)) {
                    toastMsg(R.string.pleaseinputwholecontent);
                    return;
                }
                String[] vs = adapter.getValues();
                MonitorKindBean monitorKindBean = adapter.getMonitorKindBean();
                List<MonitorInputValueBean> values = new ArrayList<>();
                for (int i = 0; i < vs.length; i++) {
                    if (TextUtils.isEmpty(vs[i])) {
                        toastMsg(R.string.pleaseinputwholecontent);
                        return;
                    }
                    double max = 0;
                    if ("".equals(monitorKindBean.getMaxValue())) {
                        max = 0;
                    } else {
                        max = Double.valueOf(monitorKindBean.getMaxValue());
                    }
                    double min = 0;
                    if ("".equals(monitorKindBean.getMinValue())) {
                        min = 0;
                    } else {
                        min = Double.valueOf(monitorKindBean.getMinValue());
                    }
                    double input = Double.valueOf(vs[i]);
                    if (input < min || input > max) {
                        toastMsg(R.string.inputoutofperiod);
                        return;
                    }
                    MonitorInputValueBean value = new MonitorInputValueBean();
                    value.setValue(vs[i]);
                    if (monitorKindBean.getValueList() != null && monitorKindBean.getValueList().size() > 0) {
                        value.setValueId(monitorKindBean.getValueList().get(i).getValueId());
                    } else {
                        value.setValueId(testId);
                    }
                    values.add(value);
                }
                loading();
                long datel = 0;
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date d = sdf.parse(time + ":00");
                    datel = d.getTime();
                } catch (ParseException e) {

                }
                YiJiaHuNetWorkUtils.patientMonitorAdd(datel + "", monitorId, testId, values, handler);

                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                break;
            case R.id.tv_easynotice_func:
                popup_easynotice.dismiss();
                finish();
                break;
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            String[] vss = adapter.getValues();
            boolean isSet = false;//是否有输入内容
            for (int i = 0; i < vss.length; i++) {
                if (!TextUtils.isEmpty(vss[i])) {
                    isSet = true;
                    break;
                }
            }
            if (!tv_time.getText().toString().trim().equals(currentDate)) {
                isSet = true;
            }
            if (isSet) {
                tv_easynotice_title.setText(getResources().getString(R.string.data_exit));
                tv_easynotice_cancel.setText(getResources().getString(R.string.cancel));
                tv_easynotice_func.setText(getResources().getString(R.string.data_sure));
                popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(this);
            } else {
                finish();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


}
